package com.ksp.wke.kspm01;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

import static com.ksp.com.KSPCOM_BasConst.*;

import org.apache.lucene.queries.CommonTermsQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ksp.api.SpringUtil;

/**
 * 评论新增线程
 * @author anye
 *
 */
public class KSPM01Thd implements Runnable{
	
	private Logger log = LoggerFactory.getLogger(KSPM01Thd.class);

	ConcurrentLinkedQueue<Map<String, Object>> cmtQue = new ConcurrentLinkedQueue<>();
	
	public static ReentrantLock cmtDealLock = new ReentrantLock(true);	
	
	public KSPM01Thd() {
	}
	
	public KSPM01Thd(ConcurrentLinkedQueue<Map<String, Object>> pCmtQue) {
		this.cmtQue = pCmtQue;
	}
	
	@Override
	public void run() {
		while (!cmtQue.isEmpty()) {
			try {
				cmtDealLock.lock();
				Iterator<Map<String, Object>> cmtQueIte = cmtQue.iterator();
				while (cmtQueIte.hasNext()) {
					Map<String, Object> wCmtQueMap = cmtQueIte.next();
					exeCmtAddService(wCmtQueMap);
					cmtQue.poll();
				} 
			} catch (Exception e) {
				log.error(e.getMessage());
			} finally {
				cmtDealLock.unlock();
			}
		}
	}

	/**
	 * 多线程处理文章评论新增
	 * @param pCmtQueMap
	 */
	private void exeCmtAddService(Map<String, Object> pCmtQueMap) {
		KSPM01Mapper kspm01Mapper = SpringUtil.getBean(KSPM01Mapper.class);
		int wCmtQrgInt = ORG_TCH;
		List<Map<String, Object>> wCmtTchLst = kspm01Mapper.qryMaxArtCmtTch(pCmtQueMap);
		if (wCmtTchLst != null && wCmtTchLst.size() > 0) {
			Map<String, Object> wCmtMap = wCmtTchLst.get(0);
			if (wCmtMap != null) {
				int wMaxTchInt = Integer.parseInt( wCmtMap.get(TCH_IDN).toString());
				if (wCmtQrgInt <= wMaxTchInt) {
					wCmtQrgInt = wMaxTchInt + 1;
				}
			}
		}
		
		pCmtQueMap.put(CMT_TCH, wCmtQrgInt);
		int insArtCmt = kspm01Mapper.insArtCmt(pCmtQueMap);
		if (insArtCmt > 0) {
			log.info(pCmtQueMap.get(CMT_OAM) + "评论"+ pCmtQueMap.get(TTL_TCH) +"成功");
		}
	}
}
